package com.example.teacherservice.service;

import com.example.teacherservice.entity.User;
import com.example.teacherservice.exception.BusinessException;
import com.example.teacherservice.exception.ResourceNotFoundException;
import com.example.teacherservice.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
@RequiredArgsConstructor
public class UserService {

    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;


    public User findByUsername(String username) {
        if (!StringUtils.hasText(username)) {
            throw new IllegalArgumentException("Username cannot be empty");
        }
        return userRepository.findByUsername(username)
                .orElseThrow(() -> new ResourceNotFoundException("User not found with username: " + username));
    }

    public User findById(Long id) {
        if (id == null || id <= 0) {
            throw new IllegalArgumentException("Invalid user ID");
        }
        return userRepository.findByIdAndDeleted(id, 0)
                .orElseThrow(() -> new ResourceNotFoundException("User not found with id: " + id));
    }

    public User createUser(User user) {
        if (user == null) {
            throw new IllegalArgumentException("User cannot be null");
        }

        if (!StringUtils.hasText(user.getUsername())) {
            throw new BusinessException("Username is required");
        }

        if (!StringUtils.hasText(user.getPassword())) {
            throw new BusinessException("Password is required");
        }

        if (userRepository.existsByUsernameAndDeleted(user.getUsername(), 0)) {
            throw new BusinessException("Username already exists");
        }

        // 自动加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.setDeleted(0);
        return userRepository.save(user);
    }

    public User updateUser(Long id, User userDetails) {
        User user = findById(id);

        if (userDetails.getUsername() != null) {
            if (userRepository.existsByUsernameAndDeletedAndIdNot(
                    userDetails.getUsername(), 0, id)) {
                throw new BusinessException("Username already taken");
            }
            user.setUsername(userDetails.getUsername());
        }

        if (userDetails.getPassword() != null) {
            user.setPassword(passwordEncoder.encode(userDetails.getPassword()));
        }

        if (userDetails.getPic() != null) {
            user.setPic(userDetails.getPic());
        }

        if (userDetails.getRole() != null) {
            user.setRole(userDetails.getRole());
        }

        return userRepository.save(user);
    }

    public void deleteUser(Long id) {
        User user = findById(id);
        user.setDeleted(1);
        userRepository.save(user);
    }

    public List<User> findAllActiveUsers() {
        return userRepository.findByDeleted(0);
    }
}